//
//  SVAPIReqeust.m
//  ShortVideo-ccinon
//
//  Created by LIN TONG on 2017/7/4.
//  Copyright © 2017年 LIN TONG. All rights reserved.
//

#import "SVAPIReqeust.h"
#import "SVConfig.h"
#import <ProgressHUD.h>

@implementation SVAPIReqeust

+ (void)svRequestAPI:(NSString *)url
              method:(NSString *)method
          parametors:(NSDictionary *)params
     completionBlock:(APIRequestCompletionBlock)block{
    SVAPIReqeust *reqeust = [[SVAPIReqeust alloc]init];
    [reqeust request:url withMethod:method parametors:params completionBlock:^(NSString *requestURL, BOOL success, NSDictionary *data, NSError *error) {
        block(requestURL,success,data,error);
    }];
}

- (void)request:(NSString *)url withMethod:(NSString *)method parametors:(NSDictionary *)params completionBlock:(APIRequestCompletionBlock)block{
    
    NSMutableDictionary *header = [NSMutableDictionary dictionary];
    [header setObject:[NSString stringWithFormat:@"iPhone %@",[UIDevice currentDevice].systemVersion] forKey:@"X-AGENT"];
    [header setObject:[SVCommon getClientUUID] forKey:@"X-UUID"];
    NSString *token = [JNKeychain loadValueForKey:SV_USER_TOKEN];
    if(token && [token length]>0){
        [header setObject:token forKey:@"X-TOKEN"];
    }else{
        [header setObject:@"" forKey:@"X-TOKEN"];
    }
    
    //[ProgressHUD show:@"加载中..." Interaction:NO];
    if([method isEqualToString:@"POST"]){
        ASIFormDataRequest *formRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:url]];
        [formRequest setRequestMethod:method];
        formRequest.useCookiePersistence = NO;
        NSArray *keys = [params allKeys];
        for(NSString *key in keys){
            [formRequest setPostValue:[params objectForKey:key] forKey:key];
        }
        
        formRequest.requestHeaders = header;
        
        __weak ASIFormDataRequest *request = formRequest;
        [formRequest setCompletionBlock:^{
            [ProgressHUD dismiss];
            
            NSString *json = [request responseString];
            NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
            NSError *err;
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                 
                                                                options:NSJSONReadingMutableContainers
                                 
                                                                  error:&err];
            if(!err){
                NSString *code = [dic objectForKey:@"code"];
                if([code isEqualToString:@"OK"]){
                    block(url,YES,dic,nil);
                }else{
                    if([code isEqualToString:@"e.101001"]){
                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"请求地址未找到" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
                        [alert show];
                    }else if([code isEqualToString:@"e.101002"]){
                        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"未登录或者登录过期" message:nil preferredStyle:UIAlertControllerStyleAlert];
                        
                        UIAlertAction *OK = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                            [alert dismissViewControllerAnimated:YES completion:nil];
                            [APPDELEGATE showLoginVC];
                        }];
                        [alert addAction:OK];
                        [APPDELEGATE.window.rootViewController presentViewController:alert animated:YES completion:nil];
                    }else if([code isEqualToString:@"e.500"]){
                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Internal Server Error" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
                        [alert show];
                    }
                    block(url,NO,dic,nil);
                }
            }else{
                block(url,NO,nil,nil);
            }
        }];
        
        [formRequest setStartedBlock:^{
            NSLog(@"开始请求");
        }];
        
        [formRequest setFailedBlock:^{
            [ProgressHUD dismiss];
            NSLog(@"请求失败!%@",request.error);
        }];
        
        [formRequest setHeadersReceivedBlock:^(NSDictionary *responseHeaders) {
            NSLog(@"%@",request.responseHeaders);
            NSString *token = [responseHeaders objectForKey:@"X-TOKEN"];
            if(token && [token length]>0){
                [JNKeychain saveValue:token forKey:SV_USER_TOKEN];
            }
        }];
        
        [formRequest startAsynchronous];
    }else{
        NSString *new = [NSString stringWithFormat:@"%@?",url];
        NSArray *keys = [params allKeys];
        for (int i=0;i<keys.count;i++){
            NSString *key = keys[i];
            if(i == keys.count-1){
                new = [new stringByAppendingString:[NSString stringWithFormat:@"%@=%@",key,[params objectForKey:key]]];
            }else{
                new = [new stringByAppendingString:[NSString stringWithFormat:@"%@=%@&",key,[params objectForKey:key]]];
            }
        }
        
        ASIHTTPRequest *asiRequest = [[ASIHTTPRequest alloc]initWithURL:[NSURL URLWithString:new]];
        [asiRequest setRequestMethod:method];
        asiRequest.useCookiePersistence = NO;
        asiRequest.requestHeaders = header;
        
        __weak ASIHTTPRequest *request = asiRequest;
        //[ProgressHUD show:@"加载中..." Interaction:NO];
        
        [asiRequest setCompletionBlock:^{
            [ProgressHUD dismiss];
            
            NSString *json = [request responseString];
            NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
            NSError *err;
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                 
                                                                options:NSJSONReadingMutableContainers
                                 
                                                                  error:&err];
            if(!err){
                NSString *code = [dic objectForKey:@"code"];
                if([code isEqualToString:@"OK"]){
                    block(url,YES,dic,nil);
                }else{
                    if([code isEqualToString:@"e.101001"]){
                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"请求地址未找到" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
                        [alert show];
                    }else if([code isEqualToString:@"e.101002"]){
                        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"未登录或者登录过期" message:nil preferredStyle:UIAlertControllerStyleAlert];
                        
                        UIAlertAction *OK = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                            [alert dismissViewControllerAnimated:YES completion:nil];
                             [APPDELEGATE showLoginVC];
                        }];
                        [alert addAction:OK];
                        [APPDELEGATE.window.rootViewController presentViewController:alert animated:YES completion:nil];
                    }else if([code isEqualToString:@"e.500"]){
                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Internal Server Error" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
                        [alert show];
                    }else{
                        block(url,NO,dic,nil);
                    }
                }
            }else{
                block(url,NO,nil,nil);
            }
        }];
        
        [asiRequest setStartedBlock:^{
            NSLog(@"开始请求");
        }];
        
        [asiRequest setFailedBlock:^{
            [ProgressHUD dismiss];
            
            NSLog(@"请求失败!%@",request.error);
        }];
        
        [asiRequest setHeadersReceivedBlock:^(NSDictionary *responseHeaders) {
            
            NSLog(@"%@",request.responseHeaders);
            NSString *token = [responseHeaders objectForKey:@"X-TOKEN"];
            if(token && [token length]>0){
                [JNKeychain saveValue:token forKey:SV_USER_TOKEN];
            }
        }];
        
        [asiRequest startAsynchronous];
    }
}
@end
